<?php


namespace App\Services;

use App\Models\CashApply;
use App\Models\Escort;
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Log;

/**
 * 公众号模板消息
 * Class OfficialTemplateService
 * @package App\Services
 */
class OfficialTemplateService
{
    private static $appid = 'wxd8b48551d9abe8dc';

    const RECHARGE_BALANCE_TO_CUSTOMER = '1czirbuZYPA_DrWrvoGThyF-zoU8T44RQOL12rUwxyY';
    const WITHDRAW_SUCCESS_TO_CUSTOMER = 'IqLv9AojvUyJiW0Gh2tJDNgZ9Voca8MMcdDXFa1bZro';
    const WITHDRAW_FAIL_TO_CUSTOMER = '37ogltFgxl2TeeA9seDItwnCbG34JesCOyvl3wiS4_I';
    const CREATE_ORDER_TO_CUSTOMER = "V56FwTAsUXKasZQ9V6npW3CW4uMFBRLYwHjhhErMkEw";
    const ORDER_RECEIVE_TO_CUSTOMER = "Eh5gk8JKnpVcYFk-kE1Dix91qXz8yBHMtUnpnLXkFaM";
    const ORDER_DELIVERY_TO_CUSTOMER = "6Zt-XU3gCctZ967HJFs925h-nR7pzimDOGMydz15cC4";

    public static function getConstants($code = '')
    {
        $oClass = new \ReflectionClass(__CLASS__);
        $stants = $oClass->getConstants();
        if ($code) return isset($stants[$code]) ? $stants[$code] : '';
        else return $stants;
    }

    /**
     * @param Order $order
     */
    public static function rechargeBalanceSuccess($order)
    {
        $accountPage = "/home/pages/escort_center/index";

        $miniprogram = [
            'pagepath' => $accountPage
        ];
        $data['first'] = "充值到账";

        $data['keyword1'] = $order->user->mobile;
        $data['keyword2'] = $order->pay_price;
        $data['keyword3'] = '充值成功';
        $data['remark'] = "充值成功，稍后查看到账情况";

        return self::sendOut('RECHARGE_BALANCE_TO_CUSTOMER', $order->uid, $data, $miniprogram);
    }

    /**
     * 提现成功通知
     * @param CashApply $cashApply
     * @return boolean
     */
    public static function sendWithdrawSuccess($cashApply)
    {
        $accountPage = "/home/pages/escort_center/index";

        $miniprogram = [
            'pagepath' => $accountPage
        ];
        $data['first'] = "您申请的提现金额已到帐.";

        if($cashApply->type == 'bank'){
            $cashType = '银行卡';
        }elseif($cashApply->type == 'alipay'){
            $cashType = '支付宝';
        }else{
            $cashType = '微信';
        }

        $data['keyword1'] = date('Y-m-d H:i', $cashApply->created_at);
        $data['keyword2'] = $cashType;
        $data['keyword3'] = bcadd($cashApply->commission, $cashApply->balance,2);
        $data['keyword4'] = $cashApply->commission;
        $data['keyword5'] = $cashApply->balance;
        $data['remark'] = "感谢你的使用.";

        return self::sendOut('WITHDRAW_SUCCESS_TO_CUSTOMER', $cashApply->uid, $data, $miniprogram);
    }

    /**
     * 提现审核失败通知
     * @param $cashApply
     * @return boolean
     */
    public static function sendWithdrawFail($cashApply)
    {
        $accountPage = "/home/pages/escort_center/index";

        $miniprogram = [
            'pagepath' => $accountPage
        ];
        $data['first'] = "你发起来的提现失败了";

        $data['keyword1'] = bcadd($cashApply->commission, $cashApply->balance,2);
        $data['keyword2'] = date('Y-m-d H:i', $cashApply->created_at);;
        $data['keyword3'] = $cashApply->fail_msg;
        $data['remark'] = "请您按照失败原因修改相关信息后，重新提现!";

        return self::sendOut('WITHDRAW_FAIL_TO_CUSTOMER', $cashApply->uid, $data, $miniprogram);
    }

    /**
     * 商家订单提醒
     * @param Order $order
     */
    public static function sendNewOrder($order)
    {
        $orderDetailPage = "/order/pages/order_detail/index?id={$order->order_id}";

        $miniprogram = [
            'pagepath' => $orderDetailPage
        ];

        $data['first'] = "您发往{$order->school->address}的快递已通知快递员揽收，请留意";

        $data['keyword1'] = $order->order_id;
        $data['keyword2'] = "尽快";
        $data['remark'] = "点击“详情”查询进度。";

        return self::sendOut('CREATE_ORDER_TO_CUSTOMER', $order->uid, $data, $miniprogram);
    }

    /**
     * 接单通知
     * @param Order $order
     * @return boolean
     */
    public static function sendReceiveOrder($order)
    {
        $orderDetailPage = "/order/pages/order_detail/index?id={$order->order_id}";

        $miniprogram = [
            'pagepath' => $orderDetailPage
        ];

        $data['first'] = "您好，你的订单成功接单";

        $data['keyword1'] = $order->order_id;
        $data['keyword2'] = date('Y-m-d H:i');
        $data['keyword3'] = $order->escort->realname;
        $data['keyword4'] = $order->escort->phone;
        $data['remark'] = "您的订单已在完成中，请耐心等待接单人的服务";

        return self::sendOut('ORDER_RECEIVE_TO_CUSTOMER', $order->uid, $data, $miniprogram);
    }

    /**
     * 订单送达
     * @param Order $order
     */
    public static function sendDeliveryOrder($order)
    {
        $orderDetailPage = "/order/pages/order_detail/index?id={$order->order_id}";

        $miniprogram = [
            'pagepath' => $orderDetailPage
        ];

        $data['first'] = "您好，你的订单已送达";

        $data['keyword1'] = $order->order_id;
        $data['keyword2'] = $order->escort->realname;
        $data['keyword3'] = $order->escort->phone;
        $data['keyword4'] = date('Y-m-d H:i');
        $data['remark'] = "感谢你的使用。";

        return self::sendOut('ORDER_DELIVERY_TO_CUSTOMER', $order->uid, $data, $miniprogram);
    }

    /**
     * 发送模板消息
     * @param string $tempCode 模板消息常量名称
     * @param int $uid 用户uid
     * @param array $data 模板内容
     * @param array $mini 小程序跳转
     * @return bool
     */
    public static function sendOut($tempCode, $uid = null, $data = null, $mini = [])
    {
        try {
            $user = User::getByUid($uid);
            $openid = $user['wxapp_openid'];
            $app = WechatService::miniprogram();
            $templateId = self::getConstants($tempCode);
            if (!$openid) {
                Log::error("公众号模版消息,用户{$uid} openid为空");
                return false;
            }
            $res = $app->uniform_message->send([
                'touser' => $openid,
                'mp_template_msg' => [
                    'appid' => self::$appid,
                    'template_id' => $templateId,
                    'miniprogram' => $mini,
                    'data' => $data,
                ]
            ]);
            if($res['errcode'] != 0){
                Log::error("公众号模版消息发送失败" . $res['errmsg']);
            }
        }catch (\Exception $e) {
            Log::error("公众号模版消息发送失败" . $e->getMessage());
            return false;
        }
    }
}